import 'package:aio/aio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:app/generated/app_strings.dart';
import 'package:app/src/http/bean/wroks/attachment_bean.dart';
import 'package:app/src/http/bean/wroks/contract_bean.dart';
import 'package:app/src/http/bean/wroks/customers_copyInfo.dart';
import 'package:app/src/http/bean/wroks/product_bean.dart';
import 'package:app/src/ui/app_ui.dart';
import 'package:app/src/ui/route/helper/route_helper.dart';
import 'package:app/src/ui/route/works/public/items/ui_base.dart';
import 'package:app/src/ui/route/works/public/items/ui_card.dart';
import 'package:app/src/utils/image_path_utils.dart';

import '../../../../dialog/dailog.dart';

///产品信息搜索条件
class SearchProduct {
  ///产品名称
  String? ProductName = "";

  List<RollerBean> _ProductName = [];
  RollerBean? ProductNameRollBean = null;

  List<RollerBean> getProductNames(List<Product>? data) {
    if (_ProductName.length > 0) {
      return _ProductName;
    }
    List<String> _strings = [];

    //添加一行空数据
    RollerBean bean = RollerBean();
    bean.key = "";
    bean.value = "";
    _ProductName.add(bean);
    _strings.add(bean.value ?? "");

    data?.forEach((element) {
      if (!_strings.contains(element.ProductName) &&
          StringUtils.isNotEmpty(element.ProductName)) {
        RollerBean bean = RollerBean();
        bean.key = element.ProductName;
        bean.value = element.ProductName;
        _ProductName.add(bean);
        _strings.add(bean.value ?? "");
      }
    });
    return _ProductName;
  }

  ///产品类型
  String? ProductClassName = "";

  String? getProductClassName(BuildContext context) {
    if (StringUtils.isEmpty(ProductClassName)) {
      //点击选择产品类型
      return AppStrings.of(context).ClicProductClassName;
    }
    return ProductClassName;
  }

  List<RollerBean> _ProductClassNames = [];
  RollerBean? ProductClassRollBean = null;

  List<RollerBean> getProductClassNames(List<Product>? data) {
    if (_ProductClassNames.length > 0) {
      return _ProductClassNames;
    }
    List<String> _strings = [];
    //添加一行空数据
    RollerBean bean = RollerBean();
    bean.key = "";
    bean.value = "";
    _ProductClassNames.add(bean);
    _strings.add(bean.value ?? "");
    data?.forEach((element) {
      if (!_strings.contains(element.ProductClassName) &&
          StringUtils.isNotEmpty(element.ProductClassName)) {
        RollerBean bean = RollerBean();
        bean.key = element.ProductClass;
        bean.value = element.ProductClassName;
        _ProductClassNames.add(bean);
        _strings.add(bean.value ?? "");
      }
    });
    return _ProductClassNames;
  }

  ///单价
  String? ProductPrice = "";

  String? getProductPrice(BuildContext context) {
    if (StringUtils.isEmpty(ProductPrice)) {
      //点击选择单价
      return AppStrings.of(context).ClicProductPrice;
    }
    return ProductPrice;
  }

  List<RollerBean> _ProductPrice = [];
  RollerBean? ProductPriceRollBean = null;

  List<RollerBean> getProductPrices(List<Product>? data) {
    if (_ProductPrice.length > 0) {
      return _ProductPrice;
    }
    List<String> _strings = [];
    //添加一行空数据
    RollerBean bean = RollerBean();
    bean.key = "";
    bean.value = "";
    _ProductPrice.add(bean);
    _strings.add(bean.value ?? "");
    data?.forEach((element) {
      if (!_strings.contains(element.ProductPrice) &&
          StringUtils.isNotEmpty(element.ProductPrice)) {
        RollerBean bean = RollerBean();
        bean.key = element.ProductPrice;
        bean.value = element.ProductPrice;
        _ProductPrice.add(bean);
        _strings.add(bean.value ?? "");
      }
    });
    return _ProductPrice;
  }

  ///审核状态
  String? StatusName = null;

  String? getStatusName(BuildContext context, List<Product>? data) {
    if (StatusName == null) {
      var _StatusName = null;
      var isAllSame = true; //审核状态是否全部相同；全部相同；则默认赋值审核状态；
      data?.forEach((element) {
        if (isAllSame) {
          if (_StatusName == null) {
            _StatusName = element.StatusName;
          } else if (_StatusName != element.StatusName) {
            isAllSame = false;
          }
        }
      });
      if (isAllSame && StringUtils.isNotEmpty(_StatusName)) {
        StatusName = _StatusName;
        RollerBean bean = RollerBean();
        bean.key = StatusName;
        bean.value = StatusName;
        StatusNameRollBean = bean;
        return StatusName;
      }
    }
    if (StringUtils.isEmpty(StatusName)) {
      //点击选择审核状态
      return AppStrings.of(context).ClickAuditStatus;
    }
    return StatusName;
  }

  List<RollerBean> _StatusName = [];
  RollerBean? StatusNameRollBean = null;

  List<RollerBean> getStatusNames(List<Product>? data) {
    if (_StatusName.length > 0) {
      return _StatusName;
    }
    List<String> _strings = [];
    //添加一行空数据
    RollerBean bean0 = RollerBean();
    bean0.key = "";
    bean0.value = "";
    _StatusName.add(bean0);
    _strings.add(bean0.value ?? "");
    //未审核
    RollerBean bean2 = RollerBean();
    bean2.key = "未审核";
    bean2.value = "未审核";
    _StatusName.add(bean2);
    _strings.add(bean2.value ?? "");
    //审核中
    RollerBean bean3 = RollerBean();
    bean3.key = "审核中";
    bean3.value = "审核中";
    _StatusName.add(bean3);
    _strings.add(bean3.value ?? "");
    //已审核
    RollerBean bean = RollerBean();
    bean.key = "已审核";
    bean.value = "已审核";
    _StatusName.add(bean);
    _strings.add(bean.value ?? "");
    data?.forEach((element) {
      if (!_strings.contains(element.StatusName) &&
          StringUtils.isNotEmpty(element.StatusName)) {
        RollerBean bean = RollerBean();
        bean.key = element.StatusName;
        bean.value = element.StatusName;
        _StatusName.add(bean);
        _strings.add(bean.value ?? "");
      }
    });
    return _StatusName;
  }

  List<Product>? getDatas(List<Product>? data) {
    if (StringUtils.isEmpty(ProductName) &&
        StringUtils.isEmpty(ProductClassName) &&
        StringUtils.isEmpty(ProductPrice) &&
        StringUtils.isEmpty(StatusName)) {
      return data;
    }
    List<Product>? searchData = [];
    data?.forEach((element) {
      var has = true;
      if (StringUtils.isNotEmpty(ProductName)) {
        //产品名称
        if (element?.ProductName?.contains(ProductName!) ?? false) {
          //包含
        } else {
          //不包含
          has = false;
        }
      }
      if (has && StringUtils.isNotEmpty(ProductClassName)) {
        //产品类型
        if (element?.ProductClassName?.contains(ProductClassName!) ?? false) {
          //包含
        } else {
          //不包含
          has = false;
        }
      }
      if (has && StringUtils.isNotEmpty(ProductPrice)) {
        //单价
        if (element?.ProductPrice?.contains(ProductPrice!) ?? false) {
          //包含
        } else {
          //不包含
          has = false;
        }
      }
      if (has && StringUtils.isNotEmpty(StatusName)) {
        //审核状态
        if (element?.StatusName?.contains(StatusName!) ?? false) {
          //包含
        } else {
          //不包含
          has = false;
        }
      }
      if (has) {
        searchData.add(element);
      }
    });
    return searchData;
  }
}

///产品信息
// bool isContractoryalty = false; //是否为提成比例审核跳转过来的产品信息
class UiProduct {
  static Widget build(BuildContext context, SearchProduct? search,
      List<Product>? data, List<Product>? oldData, bool isContractoryalty) {
    if (StringUtils.isEmpty(data)) {
      return AppUi.getEmptyView();
    }
    StateSetter? _setState = null;
    return StatefulBuilder(builder: (context, setState) {
      _setState = setState;
      List<Widget> children = [];
      children.add(UiBase.title(
          context, AppStrings.of(context).ProductInformation,
          bottom: AppEdgeInsets.margin_bottom)); //标题
      ///产品名称
      var ProductName = StatefulBuilder(builder: (context, setState) {
        return UiBase.itemWithEdit(
          context, AppStrings.of(context).ProductName,
          search?.ProductName, null,
          isChangeColor: false,
          isNumber: false,
          isEmpty: true,
          isDecimal: false,
          suffixIcon: Container(
            alignment: Alignment.center,
            width: 85,
            child: MaterialButton(
              onPressed: () {
                var rollDatas = search?.getProductNames(data);
                if (rollDatas != null && rollDatas.length > 0) {
                  AppDialog.showDialogWithRollerPicker(context,
                          datas: rollDatas, data: search?.ProductNameRollBean)
                      ?.then((value) {
                    //print("===========工厂$value");
                    if (value != null) {
                      // search?.ProductName = value.value;
                      // search?.ProductNameRollBean = value;
                      //不自动刷新了，让他点击搜索按钮之后再刷新
                      //_setState
                      setState?.call(() {
                        search?.ProductName = value.value;
                        search?.ProductNameRollBean = value;
                      });
                    }
                  });
                }
              },
              padding: EdgeInsets.only(left: 2, right: 2, top: 0, bottom: 0),
              height: 32,
              child: Text(
                AppStrings.of(context).ClickSelect,
                style: TextStyle(color: Colors.white),
              ),
              color: Colors.blueAccent,
            ),
          ),
          onChanged: (value) {
            search?.ProductName = value;
          },
          // focusNode: FocusNodeUtils().addListener((value) {
          //   if (!value) {
          //     _setState?.call(() {});
          //   }
          // })
        );
      });
      children.add(ProductName);

      ///产品类型
      var ProductClassName = StatefulBuilder(builder: (context, setState) {
        return UiBase.item(context, AppStrings.of(context).ProductClassName,
            search?.getProductClassName(context), null,
            isChangeColor: false, isBlue: true, isAllowEmpty: true, onTap: () {
          var rollDatas = search?.getProductClassNames(data);
          if (rollDatas != null && rollDatas.length > 0) {
            AppDialog.showDialogWithRollerPicker(context,
                    datas: rollDatas, data: search?.ProductClassRollBean)
                ?.then((value) {
              //print("===========工厂$value");
              if (value != null) {
                // search?.ProductClassName = value.value;
                // search?.ProductClassRollBean = value;
                //不自动刷新了，让他点击搜索按钮之后再刷新
                //_setState
                setState?.call(() {
                  search?.ProductClassName = value.value;
                  search?.ProductClassRollBean = value;
                });
              }
            });
          }
        });
      });
      children.add(ProductClassName);

      ///单价
      var ProductPrice = StatefulBuilder(builder: (context, setState) {
        return UiBase.item(context, AppStrings.of(context).ProductPrice,
            search?.getProductPrice(context), null,
            isChangeColor: false, isBlue: true, isAllowEmpty: true, onTap: () {
          var rollDatas = search?.getProductPrices(data);
          if (rollDatas != null && rollDatas.length > 0) {
            AppDialog.showDialogWithRollerPicker(context,
                    datas: rollDatas, data: search?.ProductPriceRollBean)
                ?.then((value) {
              //print("===========工厂$value");
              if (value != null) {
                // search?.ProductPrice = value.value;
                // search?.ProductPriceRollBean = value;
                //不自动刷新了，让他点击搜索按钮之后再刷新
                //_setState
                setState?.call(() {
                  search?.ProductPrice = value.value;
                  search?.ProductPriceRollBean = value;
                });
              }
            });
          }
        });
      });
      children.add(ProductPrice);

      ///审核状态
      var AuditStatus = StatefulBuilder(builder: (context, setState) {
        return UiBase.item(context, AppStrings.of(context).AuditStatus,
            search?.getStatusName(context, data), null,
            isChangeColor: false, isBlue: true, isAllowEmpty: true, onTap: () {
          var rollDatas = search?.getStatusNames(data);
          if (rollDatas != null && rollDatas.length > 0) {
            AppDialog.showDialogWithRollerPicker(context,
                    datas: rollDatas, data: search?.StatusNameRollBean)
                ?.then((value) {
              //print("===========工厂$value");
              if (value != null) {
                // search?.StatusName = value.value;
                // search?.StatusNameRollBean = value;
                //不自动刷新了，让他点击搜索按钮之后再刷新
                //_setState
                setState?.call(() {
                  search?.StatusName = value.value;
                  search?.StatusNameRollBean = value;
                });
              }
            });
          }
        });
      });
      children.add(AuditStatus);

      ///搜索
      children
          .add(UiBase.itemWithButon(context, AppStrings.of(context).search, () {
        _setState?.call(() {});
      }, margin: EdgeInsets.only(top: 8, bottom: 8)));

      ///产品数据表格
      //children.add(_table(context, data, oldData));
      children.add(
          _table(context, search?.getDatas(data), null, isContractoryalty));
      var column = UiBase.column(context, children);
      var card = UiCard.build(context, column);
      return card;
    });
  }

  static Widget _table(BuildContext context, List<Product>? data,
      List<Product>? oldData, bool isContractoryalty) {
    List<TableRow> children = [];
    //标题
    children.add(TableRow(
        //第一行，添加背景色
        decoration:
            BoxDecoration(color: AppColors.backgroundColorWithTableTitle),
        children: [
          Center(
            child: _text(AppStrings.of(context).TheSerial), //序号
          ),
          Center(
            child: _text(AppStrings.of(context).ProductId), //产品Id
          ),
          Center(
            child: _text(AppStrings.of(context).ProductName), //产品名称
          ),
          Center(
            child: _text(AppStrings.of(context).ProductClassName), //产品类型
          ),
          Center(
            child: _text(AppStrings.of(context).ProductPrice), //单价
          ),
          Center(
            child: _text(AppStrings.of(context).PriceUnitName), //计价单位
          ),
          Center(
            child: _text(AppStrings.of(context).PdOrderArea), //下单面积
          ),
          Center(
            child: _text(AppStrings.of(context).PdContractArea), //产品面积
          ),
          Center(
            child: _text(AppStrings.of(context).MinusArea), //减调面积
          ),
          Center(
            child: _text(AppStrings.of(context).PdOdQuotient), //下单面积占比
          ),
          Center(
            child: _text(AppStrings.of(context).AuditStatus), //审核状态
          ),
          Center(
            child: _text(AppStrings.of(context).Operation), //操作
          ),
        ]));
    var serial = 1;
    if (data != null && data.length > 0) {
      for (int i = 0; i < data.length; i++) {
        Product element = data[i];
        Product? mOldData = null;
        if (oldData != null && oldData.length > i) {
          mOldData = oldData?[i];
        }
        // print("ProcessInfoList:============${element.ProcessInfoList?.length}");
        // print("ProcessInfoList:============${element.ProcessInfoList}");
        // print("ProcessInfoList:============${element.ProcessInfoList?[0][0].BrandRequireImg}");
        var isOverRed = false; //超出产品面积
        var PdOrderAreaText = element.PdOrderArea ?? ""; //下单面积
        try {
          var initArea = 0.0; //期初面积
          if (StringUtils.isNotEmpty(element.InitOrderedArea)) {
            try {
              initArea = double.parse(element!.InitOrderedArea!);
            } catch (e) {}
          }
          var outproductarea = AppStrings.of(context).outproductarea; //超出产品面积
          var hanqichumianji = AppStrings.of(context).hanqichumianji; //含期初面积
          if (StringUtils.isNotEmpty(element.PdContractArea) &&
              StringUtils.isNotEmpty(element.PdOrderArea)) {
            double PdContractArea = double.parse(element!.PdContractArea!);
            double PdOrderArea = double.parse(element!.PdOrderArea!);
            if (PdContractArea != 0 && PdOrderArea > PdContractArea) {
              if (initArea > 0) {
                var str =
                    "(${outproductarea},$hanqichumianji:$initArea)"; //超出产品面积,含期初面积
                PdOrderAreaText += str;
              } else {
                var str = "(${outproductarea})"; //超出产品面积
                PdOrderAreaText += str;
              }
              isOverRed = true;
              // return _text(text, isRed: true);
            }
          } else {
            if (initArea > 0) {
              var str = "($hanqichumianji:$initArea)"; //含期初面积
              PdOrderAreaText += str;
              //return _text(text, isRed: true);
            }
          }
        } catch (e) {}
        //内容
        children.add(TableRow(
            //第一行，添加背景色
            children: [
              Center(
                child: _text((serial++).toString()), //序号
              ),
              Center(
                child: _text(element.ProductId), //产品Id
              ),
              Center(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Visibility(
                      child: Image.asset(
                        ImagePathUtils.getPathWithImageLabel("congshu.png"),
                        width: 35,
                      ),
                      visible: element.isParentProduct(), //判断是否从属
                    ),
                    Expanded(
                        child: Center(
                      child: _text(
                        element.getProductName(),
                        isBlue: true,
                        onTap: () {
                          AppRouteHelper.goProductInfoRoute(
                              context, element, mOldData, isContractoryalty);
                        },
                      ),
                    ))
                  ],
                ), //产品名称
              ),
              Center(
                child: _text(element.ProductClassName), //产品类型
              ),
              Center(
                child: _text(element.ProductPrice), //单价
              ),
              Center(
                child: _text(element.PriceUnitName), //计价单位
              ),
              Center(
                child: _text(PdOrderAreaText, isRed: isOverRed), //下单面积
              ),
              Center(
                child: _text(element.PdContractArea), //产品面积
              ),
              Center(
                child: _text(element.MinusArea), //减调面积
              ),
              Center(
                child: _text(element.PdOdQuotient, isRed: isOverRed), //下单面积占比
              ),
              Center(
                child: _text(element.getStatusName(context)), //审核
              ),
              Center(
                child: InkWell(
                  child: Container(
                    child: _text(AppStrings.of(context).ToView, isBlue: true),
                    margin: EdgeInsets.only(top: 8, bottom: 8),
                  ),
                  onTap: () {
                    AppRouteHelper.goProductInfoRoute(
                        context, element, mOldData, isContractoryalty);
                  },
                ), //查看
              ),
            ]));
      }
    }
    var table = Table(
      defaultVerticalAlignment: TableCellVerticalAlignment.middle,
      columnWidths: {
        0: FixedColumnWidth(50),
        1: FixedColumnWidth(100),
        2: FlexColumnWidth(2),
        10: FixedColumnWidth(80),
        11: FixedColumnWidth(50),
      },
      border: AppStyle.getTableBorder(),
      textDirection: TextDirection.ltr,
      children: children,
    );
    var width = 1700.0;
    if (width < px.screenWidth()) {
      width = px.screenWidth() - 60;
    }
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      physics: BouncingScrollPhysics(),
      child: Container(
        width: width,
        child: table,
      ),
    );
  }

  static Widget _text(
    String? text, {
    bool isBlue = false,
    bool isRed = false,
    GestureTapCallback? onTap,
  }) {
    TextStyle? style = null;
    if (isBlue) {
      style = AppStyle.textStyleWithCardBlue();
    } else {
      style = AppStyle.textStyleWithCard();
    }
    if (isRed) {
      style = AppStyle.textStyleWithCardRed();
    }
    if (onTap != null) {
      return InkWell(
        child: Text(
          text ?? "",
          style: style,
        ),
        onTap: () {
          onTap?.call();
        },
      );
    } else {
      return Text(
        text ?? "",
        style: style,
      );
    }
  }
}
